package cn.baiweigang.uu.api.future;

import cn.baiweigang.uu.api.BaseApi;
import cn.baiweigang.uu.enums.TransferTypeEnum;
import cn.baiweigang.uu.model.AccountInfo;
import cn.baiweigang.uu.utils.LogUtil;
import cn.baiweigang.uu.utils.StringUtil;
import com.huobi.future.api.response.transfer.FuturesTransferResponse;
import com.huobi.future.api.service.transfer.TransferApiServiceImpl;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class TransferFutureApi extends BaseApi {
    private TransferApiServiceImpl transferApiService;

    public boolean transfer(AccountInfo accountInfo, BigDecimal amount, TransferTypeEnum transferType) {
        try {
            init(accountInfo.getAccountName());
            FuturesTransferResponse response =
                    transferApiService.transfer(accountInfo.getSymbol().getCode(),
                            amount.setScale(8, BigDecimal.ROUND_DOWN), transferType.getCode());
            LogUtil.logInfo(response);
            if (response != null && StringUtil.isNotBlank(response.getStatus()) &&
                    response.getStatus().equalsIgnoreCase("ok") &&
                    Long.valueOf(response.getData().toString()) > 0) {
                LogUtil.logInfo("划转成功");
                return true;
            }
        } catch (Throwable e) {
            LogUtil.logError("交割合约和币币账户间划转异常 " + e.getMessage());
        }
        return false;
    }

    private void init(String accountName) {
        if (transferApiService == null) {
            loadByAccountName(accountName);
            transferApiService = new TransferApiServiceImpl(apiKeyInfo.getApiKey(), apiKeyInfo.getSecretKey());
        }
    }
}
